<?php

namespace App\Http\Controllers\Test;

use App\Http\Controllers\Controller;
use App\Models\Wind;
use App\Models\WindTag;


class WindController extends Controller
{
    // 风向标
    public function initialize()
    {
        parent::initialize();
    }

    // 获取风向标  将风向标标签写到标签表中
    // slh.com/test/wind/to-tag
    public function toTag()
    {
        $windDb = new Wind();
        $tagDb  = new WindTag();
        $lists  = $windDb->get()->toArray();

        // 将标签整理到风向标中
        $tagList = $tagDb->get()->toArray();
        $windTag = [];
        foreach($tagList as $item){
            $windTag[$item['wind_id']][] = $item;
        }

        // 整理标签
        foreach($lists as $item){
            $tags   = json_decode($item['tag'], true);
            $windId = $item['id'];
            $insert = $str = [];
            if(empty($tags)){
                continue;
            }

            // 将标签保存到标签表中
            $_windTag = $windTag[$windId] ?? [];
            $_windTag = array_column($_windTag, 'tag');
            foreach($tags as $_tag){
                $_tag  = trim($_tag);
                $str[] = $_tag;
                // 如果不存在 则保存在风向标标签表中
                if(!in_array($_tag, $_windTag)){
                    $insert[] = ['wind_id' => $windId, 'tag' => $_tag, 'ctime' => LARAVEL_TIME];
                }
            }

            if($str){
                $windDb->where('id', $windId)->update(['tag' => json_encode($str, JSON_UNESCAPED_UNICODE)]);
            }
            if($insert){
                $tagDb->insert($insert);
            }
        }

        return $this->success([], '风向标标签处理完成！！');
    }


}


